﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ML.Entity;
using ML.IBusiness;

namespace ML.Web.Controllers
{
    /// <summary>
    /// 订单统计
    /// </summary>
    public class OrderOverViewController : BaseController
    {
        private readonly IOrderBusiness orderBusiness;
        private readonly IMerchantBusiness merchantBusiness;
        public OrderOverViewController(IOrderBusiness _orderBusiness, IMerchantBusiness _merchantBusiness)
        {
            orderBusiness = _orderBusiness;
            merchantBusiness = _merchantBusiness;
        }

        /// <summary>
        /// 生成订单图表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOrderStatisticsData()
        {
            //todo 此方法均可以封装，请封装
            var list = new List<OrderView>();
            var merchant = merchantBusiness.GetAll().data;
            //所有商户的支付订单数量
            var merchantPayCount = new List<int>();
            var baseTime = DateTime.Now.Date;
            var timeStringList = new List<string>();

            UserInfoSession userInfoSession = UserHelper.GetCurrentUser();
            if (userInfoSession.UserType==4)//管理员，显示所有统计信息
            {
                for (int i = 0; i < 7; i++)
                {
                    var beginTime = baseTime.AddDays(-i).ToString("MM月dd");
                    timeStringList.Add(beginTime);
                }
                foreach (var data in merchant)
                {
                    //根据商户id，查询订单信息
                    var payCount = orderBusiness.GetPaidOrderForWeek(data.Id);
                    list.Add(new OrderView { name = data.Name, data = payCount.data.ToArray() });
                }
            }
            if (userInfoSession.UserType==2)//商户，显示自己的统计信息
            {
                for (int i = 0; i < 7; i++)
                {
                    var beginTime = baseTime.AddDays(-i).ToString("MM月dd");
                    timeStringList.Add(beginTime);
                }
                    //根据商户id，查询订单信息
                    var payCount = orderBusiness.GetPaidOrderForWeek(userInfoSession.MerchantId);
                    list.Add(new OrderView { name = userInfoSession.MerchantName, data = payCount.data.ToArray() });
            }
            
            return Json(new { NameArray = merchant.Select(m => m.Name).ToArray(), OrderData = list, TimeArray = timeStringList }, JsonRequestBehavior.AllowGet);
        }

        private class OrderView
        {
            /// <summary>
            /// 商户名称
            /// </summary>
            public string name { get; set; }

            /// <summary>
            /// 商户支付数量
            /// </summary>
            public int[] data { get; set; }

            /// <summary>
            /// 图表类型
            /// </summary>
            public string type { get; set; } = "bar";
        }
    }
}